'use strict'

module.exports = app => {
  class TopicService extends app.Service {
    async list(query) {
      const sql = `select reply.id, reply.content, reply.comment_id, reply.create_at,
        reply.reply_id, reply.from_uid, reply.to_uid, 
        from_user.name as from_user_name, from_user.realname as from_user_realname, 
        to_user.name as to_user_name, to_user.realname as to_user_realname
        from reply 
        inner join user as from_user 
        on reply.from_uid = from_user.id
        inner join user as to_user
        on reply.to_uid = to_user.id 
        where reply.comment_id = ?  limit ? offset ?`
      const replies = await this.app.mysql.query(sql, [ query.comment_id, query.limit, (query.page - 1) * query.limit ])
      return replies;
    }

    async create(params) {
      const reply = await this.app.mysql.insert('reply', {
        content: params.content,
        comment_id: params.comment_id,
        reply_id: params.reply_id,
        from_uid: params.from_uid,
        to_uid: params.to_uid,
      })
      if (reply.affectedRows === 1) {
        await this.app.mysql.query('UPDATE comment SET reply_count = reply_count + 1 WHERE id = ?', [ params.comment_id ])
      }
      return reply.insertId
    }

  }

  return TopicService;
};
